package top.gohigh.springboot.common;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import top.gohigh.springboot.model.Permission;
import top.gohigh.springboot.model.Role;
import top.gohigh.springboot.model.User;
import top.gohigh.springboot.service.UserService;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        User user= (User) principals.getPrimaryPrincipal();

        for(Role role:user.getRoles()){
            authorizationInfo.addRole(role.getName());
            for (Permission p:role.getPermissions()){
                authorizationInfo.addStringPermission(p.getPerm());
            }
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
       String username=(String)token.getPrincipal();
       User user=userService.getByName(username);
       if(user==null){
           return null;
       }
        SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(
                user,
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                getName()

        );
        return authenticationInfo;
    }
}
